$(document).ready(function () {
    $("body").append("<div id='DeptSelect_Panel'  style='position:absolute; z-index:10001;'></div>");
    $(document).click(function (event) {
        var element = event.target;
        var emeCls = $(element).attr("bj");
        if (emeCls != "cBj") {
            //$("#DeptSelect_Panel").css("display", "none");
        }
    });
});



// ----------------------------------------
// 部门选择器
// ----------------------------------------
(function ($) {
    $.fn.DeptSelectCtrl = function (options) {
        
        //(this).attr('bj','cBj');
        var defaults = {
            CtrolID: $(this).attr("id"),
            //evt: "click",
            divItemSelect: 'div_item_select',
            showDataDivId: "DeptSelect_Panel",
            inputDataTextId: "input_text"
        };
        if (options) {
            $.extend(defaults, options);
        }
        //初始化控件
        //添加对应样式
        $(this).wrap("<div id=\"Dept_"+defaults.CtrolID+"\" class=\"deptctrl\" style=\"width:"+(this.width()+20)+"px\"></div>");
        $(this).width(this.width()-16);
        $(this).after('<input type="button" class="button" id="btn_'+defaults.CtrolID+'"/>');
        $("#btn_"+defaults.CtrolID).click(function(event){
             fn($("#"+defaults.CtrolID).val(),event);
        })
        $("body").append("<div id='div_tree_"+defaults.CtrolID+"' style='position:absolute; z-index:10001;display:none'><ul id='tree_"+defaults.CtrolID+"' class='ztree'></ul><div>");
       
       
       
               /* 树 */
        var setting = {
                data: {
                    key: {
                        title: "t"
                    },
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    beforeClick: beforeClick,
                    onClick: onClick
                }
            };
        var log, className = "dark";
        function beforeClick(treeId, treeNode, clickFlag) {
            className = (className === "dark" ? "" : "dark");
            //showLog("[ " + getTime() + " beforeClick ]&nbsp;&nbsp;" + treeNode.name);
            return (treeNode.click != false);
        }
        function onClick(event, treeId, treeNode, clickFlag) {
            $("#"+defaults.CtrolID).val(treeNode.name);
            setValue(treeNode.id);
            hide();
       }
       //------------------------------
        
       
       
        $.fn.zTree.init($("#tree_"+defaults.CtrolID), setting, Org.rows);
        var obj = defaults.CtrolID;
        
        //在页面上显示用户选择界面
        function showPanel() {
            var tLeft = $("#"+obj).offset().left;
            var tTop = $("#"+obj).offset().top + 10;
            $("#div_tree_"+defaults.CtrolID).css({ display: "block", left: tLeft, top: tTop });
        }

       $(document).click(function (event) {
            var element = event.target;
            var id = $(element).attr("id");
            if(id==undefined || id ==null)
            {
               hide();
            }
            else if (id.indexOf("tree_"+defaults.CtrolID)<0) {
               hide();
            }
        });

        //生成部门信息
        function carHtml(vYear, vMonth, vDay, vipt) {
            
        }

        //设置选择的值
        function setValue(value) {
             $("#"+defaults.CtrolID).attr("SValue",value);
        }
        
        function getValue(value)
        {
            return  $("#"+defaults.CtrolID).attr("SValue");
        }

        function getText(value)
        {
            return  $("#"+defaults.CtrolID).attr("SText");  
        }
        $(this).click(function(event){
            fn(this.value,event);
         });
        //绑定键盘事件
        $(this).keyup(function (event) {
            fn(this.value,event);
        });

        function fn(v,event)
        {   
            if (event.keyCode == 40) {//down
                chageSelect(1);
            }
            else if (event.keyCode == 38) {//up
                chageSelect(-1);
            }
            else if (event.keyCode == 13) {//回车
                item_click($("#" + defaults.showDataDivId + " div[class='" + defaults.divItemSelect + "']"));
            }
            else if (v.length >=0) {
                registerInputEvent();
                setTimeout(showPanel,0);
            }
            else {
                $("#div_tree_"+defaults.CtrolID).slideUp(200);
            }
        }
        //.blur(function(){$("#" + showDataDivId).slideUp(200);});
        /**
        * 键盘操作  向上 或向上 
        * @param {Object} opt   向上 -1  向下 1 
        */
        function chageSelect(opt) {
            var DataDivID="#"+defaults.showDataDivId;
            if ($(DataDivID).css('display') == 'block') {
                var obj = $(DataDivID+" div[class='" + defaults.divItemSelect + "']");
                if (obj.html() == null) {//当前还未选中。
                    if (opt == 1) {
                        $("#" + defaults.showDataDivId + " div:first").addClass(defaults.divItemSelect);
                    }
                    else {
                        $("#" + defaults.showDataDivId + " div:last").addClass(defaults.divItemSelect);
                    }
                }
                else {
                    var curr = parseInt($("#" + defaults.showDataDivId + " div[class='" + defaults.divItemSelect + "'] ~ input[name='d_index']").val()) + opt;
                    var divCount = $("#" + defaults.showDataDivId + " div").size();
                    $("#" + defaults.showDataDivId + " div[class='" + defaults.divItemSelect + "']").removeClass(defaults.divItemSelect);
                    $("#" + defaults.showDataDivId + " div:eq(" + ((curr < 0) ? (divCount - 1) : ((curr == divCount) ? 0 : curr) + ")")).addClass(defaults.divItemSelect);
                }
            }
        }
        /**
        * 注册事件
        */
        function registerInputEvent() {
            $("#" + defaults.showDataDivId + " div").click(function () {
                item_click($(this));
            }).mouseover(function () {
                $("#" + defaults.showDataDivId + " div[class='" + defaults.divItemSelect + "']").removeClass(defaults.divItemSelect);
                $(this).addClass(defaults.divItemSelect);
            }).mouseout(function () {
                $(this).removeClass(defaults.divItemSelect);
            });
        }

        /**
        * 点击每一项的操作
        * @param {Object} obj
        */
        function item_click(obj) {
            //
            //debugger
            if (obj.html() == null) {//如果是按回车键。。。
                
                //暂时不做操作。。。。
            }
            else { //如果是点击 选择
                $("#"+defaults.CtrolID).val($(obj).html()).focus();
                
                //取得 你要放置的数据  d_value   为 变量名。。。
                //var currValue = $("#" + showDataDivId + " div[class='" + divItemSelect + "'] ~ input[name='d_value']").val();
            }
            //$("#" + defaults.showDataDivId).hide();
            //跳转。。。。。等 操作。
        }
        
        function hide()
        {
           $("#div_tree_"+defaults.CtrolID).css("display", "none");
        }

        function seek(key) {
            //debugger
            //var key = $("#input_div").val();
            var _a = [];
            var result = $.grep(Org.rows, function (e, n) {
                if (e.flag == '1d') { _a.push(e); }
                if (n < 5) {
                    //alert(e.Caption);
                }
            });

            function compare(a, b){  
                if(a.pId>b.pId)
                {
                    return 1;
                }
                else if (a.pId=b.pId)
                {return 0;
                }else{
                return -1;
                }
            }
            return _a.sort(compare);
        }



    }
})(jQuery);

//初始化控件
$(document).ready(function () {
        var controls = $(this).find('input,div');
        controls.each(function () {
           if ($(this).attr("ctrlType") == "Dept") {
              $(this).DeptSelectCtrl(
              {
                  RootID: ''
              });
   }
});
});

